pacman::p_load(foreign,reshape,gdata,doBy,BradleyTerry2,corrplot,arm,plotrix,gtools,httr,XML,car,stargazer,texreg,xtable,tidyverse)

setwd("")#set working directory 

### function to input data ----
rmatprocess <- function(rmatinput,party) {
  if(party=="D"){names(rmatinput) <- c("sen1","sen2","win1","win2","t")}
  else{names(rmatinput) <- c("sen1","sen2","win2","win1","t")}
  rmatinput <- rmatinput[rmatinput$sen1!="I am not familiar with these senators",] 
  rmatinput <- rmatinput[rmatinput$sen2!="I am not familiar with these senators",] 
  
  rmatinput$sen1[rmatinput$sen1=="John McCain (Arizona)"] <- "aaJohn McCain (Arizona)"
  rmatinput$sen2[rmatinput$sen2=="John McCain (Arizona)"] <- "aaJohn McCain (Arizona)"
  
  return(rmatinput)	
}

load("fall2023-gop-activists.Rdata")
newgop <- rmatprocess(rmat,"R")

### Bradley Terry model ----
runBT <- function(DATASET,allvar){
  n <- length(DATASET$sen1)
  sen1a <- as.factor(c(as.character(DATASET$sen1), as.character(allvar)))
  sen2a <- as.factor(c(as.character(DATASET$sen2), as.character(allvar)))
  
  DATASET$sen1 <- sen1a[1:n]
  DATASET$sen2 <- sen2a[1:n]
  
  BTsenate <- BTm(cbind(win1, win2), sen1, sen2, ~ sen, id = "sen", data = DATASET)
  
  BTvalues1 <- BTabilities(BTsenate)	
  
  abilities <- -1*BTvalues1[,1]
  ses <- BTvalues1[,2]
  
  scale <- max(abilities, na.rm=T)-min(abilities, na.rm=T)
  
  ADJabilities <- (abilities-min(abilities, na.rm=T))/scale
  ADJses <- ses/scale
  
  return(cbind(ADJabilities,ADJses))
}

gopvar <- as.factor(c(as.character(newgop$sen1),as.character(newgop$sen2)))
newgopout <- runBT(newgop,allvar=gopvar)
rownames(newgopout)[13] <- "Gov. Kristi Noem (R-SD)"#fixing mislabel Gov. Kristi Noem (R-SC) 

newgopsort <- newgopout[order(newgopout[,1]),]

pdf("figureA9.pdf")

plot(y=1:dim(newgopout)[1],x=newgopout[order(newgopout[,1]),1],yaxt="n",type="n",xlab="Score",ylab="",
     xlim=c(-.2,1.2),main="Perceived Ideology \n by Republicans",cex.main=1.8)
col.vec <- rep("black",dim(newgopsort)[1])
col.vec[which(rownames(newgopsort)=="Gov. Ron DeSantis (R-FL)")] <- "blue"
col.vec[which(rownames(newgopsort)=="Former governor Nikki Haley (R-SC)")] <- "blue"
col.vec[which(rownames(newgopsort)=="Former president Donald Trump (Republican)")] <- "blue"
text(y=1:dim(newgopout)[1]+.5,
     x=newgopsort[,1],
     rownames(newgopsort),cex=.55,col=col.vec)

points(y=1:dim(newgopout)[1],
       x=newgopsort[,1],pch=16)
for(i in 1:dim(newgopout)[1]){
  lines(y=c(i,i),x=c(newgopsort[i,1]-newgopsort[i,2],newgopsort[i,1]+newgopsort[i,2]))
}

dev.off()
